package paddledjl;

import ai.djl.modality.cv.Image;
import ai.djl.modality.cv.output.BoundingBox;
import ai.djl.modality.cv.output.Rectangle;

/**
 * @author 小帅丶
 * @className PaddleOCRUtil
 * @Description DJL 官方提供的工具类
 * @Date 2021-12-13-15:59
 **/
public class PaddleOCRUtil {

    /**
     * @Author 小帅丶
     * @Description 裁剪图片
     * @Date  2021-12-13 15:59
     * @param img -  原始图片
     * @param box - 每一个框的图片
     * @return ai.djl.modality.cv.Image
     **/
    public static Image getSubImage(Image img, BoundingBox box) {
        Rectangle rect = box.getBounds();
        double[] extended = extendRect(rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight());
        int width = img.getWidth();
        int height = img.getHeight();
        int[] recovered = {
                (int) (extended[0] * width),
                (int) (extended[1] * height),
                (int) (extended[2] * width),
                (int) (extended[3] * height)
        };
        return img.getSubImage(recovered[0], recovered[1], recovered[2], recovered[3]);
    }

    /**
     * @Author 小帅丶
     * @Description 对框选区域进行计算中心位置，扩大区域范围
     * @Date  2021-12-13 15:59
     * @param xmin - 原始X坐标
     * @param ymin - 原始Y坐标
     * @param width - 框选的宽度 PX
     * @param height - 框选的高度 PX
     * @return double[]
     **/
    public static double[] extendRect(double xmin, double ymin, double width, double height) {
        double centerx = xmin + width / 2;
        double centery = ymin + height / 2;
        if (width > height) {
            width += height * 2.0;
            height *= 3.0;
        } else {
            height += width * 2.0;
            width *= 3.0;
        }
        double newX = centerx - width / 2 < 0 ? 0 : centerx - width / 2;
        double newY = centery - height / 2 < 0 ? 0 : centery - height / 2;
        double newWidth = newX + width > 1 ? 1 - newX : width;
        double newHeight = newY + height > 1 ? 1 - newY : height;
        return new double[] {newX, newY, newWidth, newHeight};
    }
}
